<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

class m_backoffice_actions_block_EditTargetAction extends m_backoffice_extends_FormModal
{
	public function execute()
	{
		$formValues = $this->getFormValues("form");
		$errors = array();
		$defined = array();
		$targets = array();
		
		if(isset($formValues["moduleName"]) && isset($formValues["docId"]) && isset($formValues["docLang"]))
		{
			$module = $formValues["moduleName"];
			$docId = $formValues["docId"];
			$docLang = $formValues["docLang"];
			
			$document = $this->getDocumentProvider()->getByUniqueId($docId, $docLang);
			$targetManager = f_target_Manager::getInstance();
			
			foreach($formValues as $key => $formValue)
			{
				if(!strstr($key, "check") && !in_array($key, array("moduleName", "docId", "docLang")))
				{
					$targetManager->setModule($module)->setDocument($document)->setTarget($key)->save();
				}
				
				if(strstr($key, "check"))
				{
					$origKey = substr($key,6);

					if(!isset($formValues[$origKey]))
					{
						$targetManager->setModule($module)->setDocument($document)->setTarget($origKey)->delete();
					}
				}
			}

			$errors["status"] = "success";
		}
		else
		{
			$module = $this->getRequestParameter("moduleName");
			$docId = $this->getRequestParameter("docId");
			$docLang = $this->getRequestParameter("docLang");

			$document = $this->getDocumentProvider()->getByUniqueId($docId, $docLang);
			
			$targetManager = f_target_Manager::getInstance();
			
			$docTargets = f_target_Manager::getTargetsByDocument($document);
			$targets = $targetManager->setModule($module)->setDocument($document)->getTargets();
				
			if(count($docTargets) > 0)
			{
				foreach($docTargets as $docTarget)
				{
					$defined[] = $targets[$docTarget["label"]];
					unset($targets[$docTarget["label"]]);
				}
			}
	
			if(count($targets) > 0)
			{
				foreach($targets as $key => $target)
				{
					if($target['isset'] == true)
					{
						$targets[$key]["documents"] = f_target_Manager::getDocumentsByTarget($key, $docLang);
					}
				}
			}
		}
		
		$this->addToModel("errors", $errors);
		$this->addToModel("moduleName", $module);
		$this->addToModel("document", $document);
		$this->addToModel("docTargets", $defined);
		$this->addToModel("targets", $targets);
		
		$this->setView('success');			
	}	
}